zz_

src/factorial.js

zzmq.dev@gmail.com[dev3]/mathkit[add-clamp-n-lo-hi-function-clamps-number] / src / factorial.js @ cd59ab0d Download
Ladder Summary
  • file Implements a factorial function that validates its numeric input (must be a finite integer ≥ 0) and returns the product of all positive integers up to n, or undefined for invalid inputs, and exports it.
/**
 * Computes the factorial of a non‑negative integer.
 *
 * @param {number} n - The number to compute the factorial of.
 * @returns {number|undefined} The factorial of n for valid inputs, otherwise undefined.
 */
export function factorial(n) {
  if (typeof n !== "number" || !Number.isFinite(n)) return undefined;
  if (!Number.isInteger(n)) return undefined;
  if (n < 0) return undefined;

  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}